import { useMemo, useState } from 'react';

import { Select } from '@/components/eai-design';
import { TagRender } from '@/pages/share/sub-pages/utils';

import { SelectedDataset } from '.';
import SelectDatasetModal from './SelectDatasetModal';

interface Props {
  appId: string;
  value?: SelectedDataset[];
  onChange?: (value: SelectedDataset[]) => void;
  maxTagCount?: number | 'responsive' | undefined;
}

const SelectDataset = ({ appId, value, onChange, maxTagCount = 'responsive' }: Props) => {
  const [modalOpen, setModalOpen] = useState(false);

  const options = useMemo(() => {
    return value?.map((item) => ({
      label: item.title,
      value: item.key,
    }));
  }, [value]);

  return (
    <div>
      <Select
        mode="multiple"
        maxTagCount={maxTagCount}
        options={options}
        value={value}
        style={{ width: '100%' }}
        open={false}
        onClick={() => {
          setModalOpen(true);
        }}
        placeholder="请选择知识库"
        tagRender={TagRender}
      />
      <SelectDatasetModal
        open={modalOpen}
        appId={appId}
        confirm={(values) => {
          onChange?.(values);
          setModalOpen(false);
        }}
        cancel={() => {
          setModalOpen(false);
        }}
        defaultValue={value}
      />
    </div>
  );
};

export default SelectDataset;
